package com.jin.ks;


import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.jin.ks.MainActivity;
import com.jin.ks.User;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {
    //创建显示列表的listview
    private ListView listView;

    //列表标题list
    private List<User> list, newList;

    //创建适配器对象
    private UtilDao dao;
    private MyAdapter adapter;
    private int listNum = 0;
    SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化Toolbar
        initToolbar();

        //初始化页面对象
        initWidget();

        sp = getSharedPreferences("config", Context.MODE_PRIVATE);

        DbUtil();
        showListView();


    }

    /**
     * 初始化Toolbar
     */
    private void initToolbar() {
        // TODO: Implement this method
        //找到Toolbar控件的id
        Toolbar toolbar = method();
        //设置标题
        toolbar.setTitle("快手炸了");
        //设置menu
        toolbar.inflateMenu(R.menu.menu_toolbar);
        //设置menu点击监听
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem p1) {
                // TODO: Implement this method
                //通过ItemId判断点击项
                switch (p1.getItemId()) {
                    case R.id.menu_add:
                        Intent intent = new Intent(MainActivity.this, AddData.class);
                        startActivityForResult(intent, 1);
                        break;
                    case R.id.menu_about:


                        break;
                    case R.id.menu_exit:
                        finish();
                        break;
                }
                return false;
            }
        });

    }

    private Toolbar method() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        return toolbar;
    }

    /**
     * 初始化控件
     */
    private void initWidget() {
        listView = findViewById(R.id.main_list_view);
        newList = new ArrayList<>();
        list = new ArrayList<>();
    }

    /**
     * 显示ListView
     */
    public void showListView() {
        //查询数据
        /**
         * 添加数据到链表中
         * **/
        list = dao.inquireData();

        /**
         * 创建并绑定适配器
         * */
        adapter = new MyAdapter(this, R.layout.list_view_item, list);
        listView.setAdapter(adapter);

        /**
         * ListView事件监听
         * */
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                dialogList();
                listNum = i;
            }
        });

        //button.setOnClickListener(this);
    }

    /**
     * 普通对话框
     */
    public void dialogNormal() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        DialogInterface.OnClickListener dialogOnClick = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                User userDel = list.get(listNum);
                switch (i) {
                    case DialogInterface.BUTTON_POSITIVE:
                        dao.delData("mName=?", new String[]{userDel.getName()});
                        refresh();
                        break;
                    case DialogInterface.BUTTON_NEGATIVE:
                        break;
                    default:
                        break;
                }
            }
        };
        builder.setTitle("删除账户数据");
        builder.setMessage("确定要删除吗？");
        builder.setPositiveButton("确定", dialogOnClick);
        builder.setNegativeButton("取消", dialogOnClick);
        builder.create().show();
    }

    /**
     * 选项列表
     */
    public void dialogList() {
        final String[] items = {"选择", "编辑", "删除"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                //拿到当前选中项的 User 对象
                User userNum = list.get(listNum);
                Intent intent;
                switch (i) {
                    case 0:
                        Toast.makeText(MainActivity.this, "选中" + userNum.getName().toString(), Toast.LENGTH_LONG).show();
                        dao.status(userNum.getName().toString());
                        refresh();
                        break;
                    case 1:
                        intent = new Intent(MainActivity.this, AddData.class);
                        //传入当前选中项的姓名和电话以在编辑页面中显示在输入框中
                        intent.putExtra("edit_name", userNum.getName().toString());
                        intent.putExtra("user", dao.inquireEditData(userNum.getName().toString()));
                        startActivityForResult(intent, 2);
                        break;
                    //弹出对话框提示是否删除
                    case 2:
                        dialogNormal();
                        break;
                    default:
                        break;
                }
            }
        });
        builder.create().show();
    }

    //刷新
    public void refresh() {
        //最后查询数据刷新列表
        getNotifyData();
    }

    //页面顶部显示ListView条目数
    public void linkmanNum() {
        //textNum.setText("("+list.size()+")");
    }

    //点击添加按钮

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.menu_add:
                //跳转到 AddData Activity 传入请求码 1

            default:
                break;
        }
    }

    public void DbUtil() {
        dao = ((MyApplication) this.getApplication()).getDao();
    }

    /**
     * 当页面回到此活动时，调用此方法，刷新ListView
     */
    @Override
    protected void onResume() {
        super.onResume();
        getNotifyData();
    }

    /**
     * 这个是用来动态刷新 *
     */
    public void getNotifyData() {
        //使用新的容器获得最新查询出来的数据
        newList = dao.inquireData();
        //清除原容器里的所有数据
        list.clear();
        //将新容器里的数据添加到原来容器里
        list.addAll(newList);
        //更新页面顶部括号里显示数据
        linkmanNum();
        //刷新适配器
        adapter.notifyDataSetChanged();
    }

    /**
     * 上一个页面传回来的值
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            //请求码为1，表示点击了添加按钮

            case 1:
                //执行添加方法
                if (resultCode == RESULT_OK) {
                    String[] key = data.getStringArrayExtra("key");
                    String[] values = data.getStringArrayExtra("values");
                    dao.addData("UserInfo", key, values);
                }
                break;
            //请求码为2，表示点击了编辑按钮
            case 2:
                //执行修改方法
                String b = "";
                if (resultCode == RESULT_OK) {
                    User user = list.get(listNum);
                    String[] value = data.getStringArrayExtra("value");
                    String[] values = {value[0], value[1], value[2], value[3], value[4], value[5], value[6], value[7], value[8], value[9], value[10], value[11], user.getName()};

                    for (String a : values) {
                        b = b + a + "\n";

                    }
                    Toast.makeText(MainActivity.this, b, Toast.LENGTH_LONG).show();
                    dao.update(values);
                    break;
                }


        }
    }


}
